// FishGameManager.cs

using cmd;
using UnityEngine;

public class FishDataManager : Singleton<FishDataManager>
{
    private const string SAVE_KEY = "FishGameData";
    public FishGameData CurrentData {get; private set;}

    protected override void OnSingletonAwake()
    {
        LoadData();
    }
    
    public void AddFish(FishSaveData newFish)
    {
        //计算价格
        CurrentData.FishCount++;
        var existing = CurrentData.collectedItems.Find(f => f.Name == newFish.Name);
        if (existing != null)
        {
            existing.Count++;
            //todo 该鱼类型 总价格++
            if (newFish.MaxValue > existing.MaxValue)
            {
                existing.MaxValue = newFish.MaxValue;
            }
            if (newFish.MaxWeight > existing.MaxWeight)
            {
                existing.MaxWeight = newFish.MaxWeight;
            }
            existing.TotalValue += newFish.MaxValue;

        }
        else
        {
            CurrentData.collectedItems.Add(newFish);
            var ha = CurrentData.collectedItems.Find(f => f.Name == newFish.Name);
            ha.Count++;
            ha.MaxValue = ha.TotalValue = newFish.MaxValue;
            ha.MaxWeight = newFish.MaxWeight;
        }

        UpdateGlobalMaxValues();
        SaveData();
    }
    
    public void UpdateGlobalMaxValues()
    {
        float globalMaxValue = 0;
        float globalMaxWeight = 0;

        foreach (var fish in CurrentData.collectedItems)
        {
            if (fish.MaxValue > globalMaxValue)
            {
                globalMaxValue = fish.MaxValue;
                CurrentData.ValueName = fish.Name;
            }
            if (fish.MaxWeight > globalMaxWeight)
            {
                globalMaxWeight = fish.MaxWeight;
                CurrentData.WeightName = fish.Name;
            }

            CurrentData.TotalValue += (int)fish.TotalValue;
        }
        CurrentData.MaxValue = globalMaxValue;
        CurrentData.MaxWeight = globalMaxWeight;
    }
    
    
    
    private void SaveData()
    {
        string json = JsonUtility.ToJson(CurrentData);
        PlayerPrefs.SetString(SAVE_KEY, json);
        PlayerPrefs.Save();
    }
    private void LoadData()
    {
        CurrentData = PlayerPrefs.HasKey(SAVE_KEY) 
            ? JsonUtility.FromJson<FishGameData>(PlayerPrefs.GetString(SAVE_KEY))
            : new FishGameData();
    }

    public void ResetData()
    {
        CurrentData = new FishGameData();
        SaveData();
    }
}